﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using Cms.BLL;
using System.Collections;
using Cms.EntLib;
using System.Text;
using System.Data;

namespace Cms.Web.CmsSystem
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class JSON : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string param = EntLib.Request.GetString("param");
            string textjson = "";
            switch (param)
            {
                case "ctrl"://控件
                    textjson = CtrlToJson();
                    break;
                case "form":
                    textjson = FormToJson();
                    break;
                case "db":
                    textjson = DBToJson();
                    break;
                case "dialog":
                    textjson = BuilderDialogJson();
                    break;

            }
            ResponseText(textjson);
        }
        public string CtrlToJson()
        {
            string type = EntLib.Request.GetString("type");
            string textjson = "[]";
            if (type == "jqgrid")
            {
                string module = EntLib.Request.GetString("act");
                if (module == "getrsslist")
                {
                    string rsslink = EntLib.Request.GetString("rsslink");
                    if (!String.IsNullOrEmpty(rsslink) && rsslink != "0")
                    {
                        rsslink = EntLib.Utiltiy.UnEscape(rsslink);
                        Model.RssBody rssBody = RssBuilder.GetRssItem(new Model.RssSource(Model.RssSourceType.Url, rsslink));
                        if (rssBody != null)
                            textjson = Json.ToGridJson(rssBody.ItemList, 1, rssBody.ItemList.Count, rssBody.ItemList.Count);
                    }
                }
                else
                {
                    Type BLLType = GetFormType(module);
                    if (BLLType != typeof(Nullable))
                    {
                        int page = EntLib.Request.GetInt("page", 0);
                        int rows = EntLib.Request.GetInt("rows", 20);
                        string sidx = EntLib.Request.GetString("sidx");
                        string sord = EntLib.Request.GetString("sord");
                        if (String.IsNullOrEmpty(sidx))
                            sidx = "Id";
                        bool direction = sord == "desc";
                        int total = 0;
                        object[] args = new object[] { page, rows, sidx, direction, total };
                        object bll = Activator.CreateInstance(BLLType);
                        object objResultlist = BLLType.GetMethod("GetPager").Invoke(bll, args);
                        IList list = (IList)objResultlist;
                        textjson = Json.ToGridJson(list, page, rows, Convert.ToInt32(args[4]));
                    }
                }
            }
            if (type == "combobox")
            {
                string module = EntLib.Request.GetString("act");
                if (module == "getallsite")
                {
                    BLL.BaseDao<Model.Rsssite, int> bll = new BaseDao<Model.Rsssite, int>();
                    IList list = bll.Find("select t.Id,t.Sitetitle from Rsssite t ", null);
                    if (list != null && list.Count > 0)
                        textjson = EntLib.Json.ToJson(list);
                }
            }
            return textjson;
        }
        public string FormToJson()
        {
            string textjson = "";
            string formid = EntLib.Request.GetString("formid");
            string recordid = EntLib.Request.GetString("recordid");
            string act = EntLib.Request.GetString("act");
            Type FormType = GetFormType(formid);
            object objBLL = Activator.CreateInstance(FormType);
            if (act == "showinfo")
            {
                object objectParam = FormType.GetMethod("ConvertToIdT").Invoke(objBLL, new object[] { recordid });
                object objlist = FormType.GetMethod("GetById").Invoke(objBLL, new object[] { objectParam, false });
                if (objlist != null)
                    textjson = Json.ToJson(objlist);
            }
            return textjson;
        }
        public string DBToJson()
        {
            string textjson = "";
            string type = EntLib.Request.GetString("type");
            string act = EntLib.Request.GetString("act");
            if (type == "info")
            {
                switch (act.ToLower())
                {
                    case "getalltable"://获取所有
                        BLL.BaseDao<Model.Sys_Datadict_Table, string> blltable = new BLL.BaseDao<Model.Sys_Datadict_Table, string>();
                        IList tablelist = blltable.Find("select t.Tablename,t.Remark from Sys_Datadict_Table t", null);
                        textjson = Newtonsoft.Json.JsonConvert.SerializeObject(tablelist);//Json.ToJson(tablelist);
                        break;
                    case "getdbtypelist":
                        textjson = "[\"" + String.Join("\",\"", EntLib.Utiltiy.GetDataType().ToArray()) + "\"]";
                        textjson = textjson.ToLower();
                        break;
                    case "getcolumns"://获取表名对应的列集合.
                        string TableName = EntLib.Request.GetString("tablename");
                        string gsql = EntLib.Request.GetString("sql");
                        gsql = HttpUtility.UrlDecode(gsql);
                        if (!String.IsNullOrEmpty(TableName))
                        {
                            BLL.BaseDao<Model.Sys_Datadict_Field, string> bllfield = new BaseDao<Cms.Model.Sys_Datadict_Field, string>();
                            IList fieldlist = bllfield.Find("select t.Fieldname,t.Caption from Sys_Datadict_Field t where t.Table.Tablename='" + TableName + "'", null);
                            //BLL.BaseDao<Model.Sys_Datadict_Field>
                            textjson = EntLib.Json.ToJson(fieldlist);//Newtonsoft.Json.JsonConvert.SerializeObject(fieldlist);
                        }
                        else if (!String.IsNullOrEmpty(gsql))
                        {
                            //BLL.BaseDao<Model.Sys_Datadict_Field, string> bllfield2 = new BaseDao<Cms.Model.Sys_Datadict_Field, string>();
                            IList listsql = BLL.PageLog.GetColumns(gsql);
                            if (listsql == null)
                                textjson = "[]";
                            else
                                textjson = EntLib.Json.ToJson(listsql);//Newtonsoft.Json.JsonConvert.SerializeObject(listsql);
                        }
                        break;
                }
            }
            return textjson;
        }

        public Type GetFormType(string formid)
        {
            Type ModelType = Core.GetModelTypeByFormID(formid);
            return Core.GetBLLTypeByFormID(formid, ModelType);
        }
        public string BuilderDialogJson()
        {
            string result = "";
            string id = Request.GetString("id");
            string type = Request.GetString("type");
            if (String.IsNullOrEmpty(id))
                return "[]";
            BLL.BaseDao<Model.Sys_Popwin, string> bll = new BaseDao<Cms.Model.Sys_Popwin, string>();
            Model.Sys_Popwin model = bll.GetById(id, false);
            if (model == null)
                return "[]";
            if (type == "list")
            {
                IList list = BLL.PageLog.QueryToList(model.Listsql);
                result = Json.TableToEasyUIJson(list);
            }
            return result;
        }

        void ResponseText(string text)
        {
            //HttpContext.Current.Response.ContentType = "text/plain";
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = -1;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(text);
            HttpContext.Current.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
